/**
 * @Author : JiGuangJie
 * @Date : 2023/1/30
 * @Time : 下午2:02
 * @Version : 1.0.0
 * @description :
 */
import Websocket from '../../util/websocket';
import {TOPIC} from '../../enum/TOPIC';
import {GisPlot, PlotTextBox, PlotTypes} from '../../../../src';
import {Point} from '../../../../src/type';
import {nanoid} from 'nanoid';
import moment from 'moment/moment';
import {createScAuth} from '../../../lib/scooper-core-auth/index.esm';
import BasePlot from '../BasePlot';




/*const debugServer = (): void => {
    console.log(plotId);
    const websocketUrl = `ws://192.168.130.53:8094/cooper-draw-server/scooper/plot?accountName=Test01&accountId=${accountId}&token=123123123&plotId=${plotId}`;
    socket = new Websocket(websocketUrl, {debug: true});
    socket.open();
    socket.onConnectSuccess = (): void => {
        console.log('连接成功的后继操作');
    };
    socket.onMessage = (data: any): void => {
        console.log('收到消息：', data);
        if (data.topic === TOPIC.INSTRUCT) {
            if (data.instructType) {
                const plotType: string = data.instructContent.type;
                if (data.instructContent && data.instructType === 'ADD') {
                    let geometry: any = null;
                    if (plotType === 'point') {
                        geometry = gisPlot?.plotDraw.createPlot(data.instructContent.type as PlotTypes, [data.instructContent.point], {});
                    } else if (plotType === 'text') {
                        const {width, height}: { width: number, height: number } = data.instructContent;
                        /!*                        const plotText: PlotTextBox = new PlotTextBox({
                                                    id: data.instructContent.id,
                                                    position: data.instructContent.position,
                                                    value: '',
                                                    width,
                                                    height,
                                                    style: {
                                                        width: `${width}px`,
                                                        height: `${height}px`
                                                    }
                                                });
                                                map.addOverlay(plotText);*!/
                        return;
                    } else {
                        geometry = gisPlot?.plotDraw.createPlot(data.instructContent.type as PlotTypes, data.instructContent.path, data.instructContent.style);
                    }
                    const feature = new ol.Feature(geometry);
                    feature.set('isPlot', true);
                    feature.set('plotType', data.instructContent.type);
                    feature.set('id', data.instructContent.id);
                    const style: any = gisPlot?.plotDraw.createStyle(data.instructContent.type as PlotTypes, data.instructContent.style);
                    feature.setStyle(style);
                    plotLayer.getSource().addFeature(feature);
                } else if (data.instructContent && data.instructType === 'MOVE') {
                    const currentEditFeature: any = plotLayer.getSource().getFeatures().find((feature: any): any => {
                        return feature.getProperties().id === data.instructContent.id;
                    });
                    const geometry: any = currentEditFeature.getGeometry();
                    let newPoints: Array<Point> = [];
                    if (plotType === 'point') {
                        newPoints = [data.instructContent.point];
                    } else if (plotType === 'text') {

                    } else {
                        newPoints = data.instructContent.path;
                    }
                    geometry.setPoints(newPoints);
                }
            }
        }
    };

    socket.onClose = (): void => {
        console.log('关闭socket了');
    };
};*/

/*

const createPlot = (): void => {

    const token = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMDIiLCJtaWQiOjM5OCwib2lkIjo1OCwiciI6MTAyLCJzbm0iOiJqZ2oiLCJkZXYiOiJ3ZWIiLCJ1c3IiOiJqZ2oiLCJ2IjoyLCJjdGkiOjEsImV4cCI6MTY3MDYzNjExNCwiZGlkIjoid2ViIiwiY2lkIjowfQ.o3p67QhtNbLQXnGpsf33ftq_inMv0NbF-E0FegHjnQ0';
    const body = {
        name: `测试标绘-${new Date().getHours()}-${new Date().getMinutes()}`,
        createId: 102
    };
    const request = new Request('/cooper-draw-server/api/data/createPlot', {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            token
        },
        method: 'post',
        body: `name=测试标绘-${new Date().getHours()}-${new Date().getMinutes()}&createId=102`
    });

    fetch(request).then(response => response.json()).then(res => {
        if (res.code === 0) {
            const {plotBaseInfo: {id}} = res.data;
            plotId = id;
            plotId = '16b9bf81-08bf-420b-a154-8cfff93e98c2';
            const preLinkRequest = new Request('/cooper-draw-server/api/data/preLink', {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    token
                },
                method: 'get'
            });

            fetch(preLinkRequest).then(response => response.json()).then(preRes => {
                console.log(res);
                console.log('plotId:', plotId, 'stateCode:', preRes.data);
                if (id && preRes.data) {
                    const websocketUrl = `ws://192.168.130.204:8080/cooper-draw-server/scooper/plot?plotId=${plotId}&stateCode=${preRes.data}`;
                    // const websocketUrl = `ws://192.168.130.53:8094/cooper-draw-server/scooper/plot?plotId=${plotId}&stateCode=${preRes.data}`;
                    socket = new Websocket(websocketUrl, {debug: true});
                    socket.open();
                    socket.onConnectSuccess = (): void => {
                        console.log('连接成功的后继操作');
                    };
                    socket.onMessage = (data: any): void => {
                        console.log('收到消息：', data);
                        if (data.topic === TOPIC.INSTRUCT) {
                            if (data.instructType) {
                                const plotType: string = data.instructContent.type;
                                if (data.instructContent && data.instructType === 'ADD') {
                                    let geometry: any = null;
                                    if (plotType === 'point') {
                                        geometry = gisPlot.plotDraw.createPlot(data.instructContent.type as PlotTypes, [data.instructContent.point], {});
                                    } else if (plotType === 'text') {
                                        const {width, height}: { width: number, height: number } = data.instructContent;
                                        const plotText: PlotTextBox = new PlotTextBox({
                                            id: data.instructContent.id,
                                            center: data.instructContent.center,
                                            value: 'test',
                                            width,
                                            height,
                                            style: data.instructContent.style
                                        });
                                        map.addOverlay(plotText);
                                        plotText.onMove = (position: any): void => {
                                            console.log(position);
                                            const plotType: string = 'text';
                                            const id: string = data.instructContent.id;
                                            const params = {
                                                topic: 'instruct',
                                                plotid: plotId,
                                                accountId: accountId,
                                                updateTime: moment(Number(new Date().getTime())).format('YYYY-MM-DD HH:mm:ss.SSS'),
                                                mapType: '1',
                                                instructType: 'MOVE',
                                                instructContent: {
                                                    id,
                                                    type: plotType,
                                                    center: position
                                                }
                                            };
                                            socket.send(params);
                                        };
                                        return;
                                    } else {
                                        geometry = gisPlot.plotDraw.createPlot(data.instructContent.type as PlotTypes, data.instructContent.path, data.instructContent.style);
                                    }
                                    const feature = new ol.Feature(geometry);
                                    feature.set('isPlot', true);
                                    feature.set('plotType', data.instructContent.type);
                                    feature.set('id', data.instructContent.id);
                                    const style: any = gisPlot.plotDraw.createStyle(data.instructContent.type as PlotTypes, data.instructContent.style);
                                    feature.setStyle(style);
                                    plotLayer.getSource().addFeature(feature);
                                } else if (data.instructContent && data.instructType === 'MOVE') {
                                    if (plotType === 'text') {
                                        const textBox: any = map.getOverlays().getArray().find((item: any): any => item.id === data.instructContent.id);
                                        textBox.setPosition(data.instructContent.center);
                                        return;
                                    }
                                    const currentEditFeature: any = plotLayer.getSource().getFeatures().find((feature: any): any => {
                                        return feature.getProperties().id === data.instructContent.id;
                                    });
                                    const geometry: any = currentEditFeature.getGeometry();
                                    console.log(geometry);
                                    let newPoints: Array<Point> = [];
                                    if (plotType === 'point') {
                                        newPoints = [data.instructContent.point];
                                    } else {
                                        newPoints = data.instructContent.path;
                                    }
                                    geometry.setPoints(newPoints);
                                }
                            }
                        }
                    };

                    socket.onClose = (): void => {
                        console.log('关闭socket了');
                    };
                }
            });
        }
    });
};

const intoPlot = (): void => {
    const plotId: string = `ddeba4f2-9d95-490f-bdff-aded17d4c4ad`;
    const token: string = `eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMDIiLCJtaWQiOjM5OCwib2lkIjo1OCwiciI6MTg1LCJzbm0iOiJqZ2oiLCJkZXYiOiJ3ZWIiLCJ1c3IiOiJqZ2oiLCJ2IjoyLCJjdGkiOjEsImV4cCI6MTY3MDMxODI3NiwiZGlkIjoid2ViIiwiY2lkIjowfQ.K49wLeKjZzZFadUACxVFKZtrpwk9yH-83_V0LnqVutQ`;
};

const sharePlot = (): void => {

};

const endPlot = (): void => {
    console.log('end plot');
};

const gisPlot: GisPlot = new GisPlot(map, {isClear: true});
// const gisPlot: GisPlot = new GisPlot(map, {zoomToExtent: true});
gisPlot.plotDraw.addListener('drawEnd', (event: any): void => {
    if (event.plotType && event.plotType === 'text') { // 文本
        const params = {
            topic: 'instruct',
            plotid: plotId,
            accountId: accountId,
            updateTime: moment(Number(new Date().getTime())).format('YYYY-MM-DD HH:mm:ss.SSS'),
            mapType: '1',
            instructType: 'ADD',
            instructContent: {
                id: nanoid(),
                type: 'text',
                ...event.data
            }
        };
        socket.send(params);
    } else {
        const {plotType}: { plotType: string } = event.feature.getProperties();
        const params = {
            topic: 'instruct',
            plotid: plotId,
            accountId: accountId,
            updateTime: moment(Number(new Date().getTime())).format('YYYY-MM-DD HH:mm:ss.SSS'),
            mapType: '1',
            instructType: 'ADD',
            instructContent: {
                id: nanoid(),
                type: plotType,
                ...event.data
            }
        };
        socket.send(params);
    }
});

gisPlot.plotEdit.addListener('moveEnd', (event: any): void => {
    console.log(event.feature.getProperties().id, event.feature.getProperties().plotType);
    const plotType: string = event.feature.getProperties().plotType;
    const id: string = event.feature.getProperties().id;
    const params = {
        topic: 'instruct',
        plotid: plotId,
        accountId: accountId,
        updateTime: moment(Number(new Date().getTime())).format('YYYY-MM-DD HH:mm:ss.SSS'),
        mapType: '1',
        instructType: 'MOVE',
        instructContent: {
            id,
            type: plotType,
            ...event.data
        }
    };
    socket.send(params);
});

gisPlot.plotEdit.addListener('deformationEnd', (event: any): void => {
    const plotType: string = event.feature.getProperties().plotType;
    const id: string = event.feature.getProperties().id;
    const params = {
        topic: 'instruct',
        plotid: plotId,
        accountId: accountId,
        updateTime: moment(Number(new Date().getTime())).format('YYYY-MM-DD HH:mm:ss.SSS'),
        mapType: '1',
        instructType: 'DEFORMATION',
        instructContent: {
            id,
            type: plotType,
            ...event.data
        }
    };
    socket.send(params);
});
*/

type LoginInfo = {
    accountId: number,
    centerId: number,
    corpId: number,
    expire: string,
    memberId: number,
    operatorId: number,
    refreshToken: string,
    token: string,
    username: string
}

// let socket: Websocket;
// let accountId: string = nanoid();

export default class Online extends BasePlot {
    private readonly _scAuth: any;
    // private readonly _socket:Websocket;
    // private _accountId:string;
    // private _plotId:string

    constructor(gisPlot: GisPlot, plotLayer: any, map: any, opts: { host: string, username: string, password: string }) {
        super(gisPlot, plotLayer, map);
        this._scAuth = createScAuth({host: opts.host});
        // @ts-ignore
        this._scAuth.login(opts.username, sha256(opts.password)).then((res: LoginInfo): void => {
            console.log(res.corpId);
        });
    }
}